package com.ruoyix.aicode.util;


import com.ruoyix.aicode.domain.PageSection;
import com.ruoyix.aicode.domain.PageStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * HTML生成工具类
 */
public class HtmlGenerationUtil {
    private static final Logger logger = LoggerFactory.getLogger(HtmlGenerationUtil.class);

    /**
     * 从模板生成骨架代码
     *
     * @param requirements 需求
     * @param pageSections 页面部分
     * @param pageStyle 页面风格
     * @param analysisContent 分析内容
     * @return 骨架代码
     */
    public static String generateSkeletonFromTemplate(String requirements, List<PageSection> pageSections,
                                                      PageStyle pageStyle, StringBuilder analysisContent) {
        logger.info("从模板生成骨架代码，pageSections大小: {}", pageSections.size());

        // 构建HTML骨架
        StringBuilder skeletonBuilder = new StringBuilder();
        skeletonBuilder.append("<!DOCTYPE html>\n");
        skeletonBuilder.append("<html lang=\"zh-CN\">\n");
        skeletonBuilder.append("<head>\n");
        skeletonBuilder.append("  <meta charset=\"UTF-8\">\n");
        skeletonBuilder.append("  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n");
        skeletonBuilder.append("  <title>").append(extractTitle(requirements)).append("</title>\n");

        // 根据UI框架选择不同的CSS库
        if ("bootstrap".equalsIgnoreCase(pageStyle.getUiFramework())) {
            skeletonBuilder.append("  <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-4Q6Gf2aSP4eDXB8Miphtr37CMZZQ5oXLH2yaXMJ2w8e2ZtHTl7GptT4jmndRuHDT\" crossorigin=\"anonymous\">\n");
            skeletonBuilder.append("  <!-- Fallback CDN -->\n");
            skeletonBuilder.append("  <link href=\"https://unpkg.com/bootstrap@5.3.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\">\n");
        } else if ("tailwind".equalsIgnoreCase(pageStyle.getUiFramework())) {
            skeletonBuilder.append("  <link href=\"https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css\" rel=\"stylesheet\">\n");
            skeletonBuilder.append("  <!-- Fallback CDN -->\n");
            skeletonBuilder.append("  <link href=\"https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css\" rel=\"stylesheet\">\n");
        } else if ("material".equalsIgnoreCase(pageStyle.getUiFramework())) {
            skeletonBuilder.append("  <link href=\"https://cdn.jsdelivr.net/npm/@material/material-components-web@14.0.0/dist/material-components-web.min.css\" rel=\"stylesheet\">\n");
            skeletonBuilder.append("  <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/icon?family=Material+Icons\">\n");
        } else {
            // 默认使用Bootstrap
            skeletonBuilder.append("  <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/css/bootstrap.min.css\" rel=\"stylesheet\">\n");
            skeletonBuilder.append("  <!-- Fallback CDN -->\n");
            skeletonBuilder.append("  <link href=\"https://unpkg.com/bootstrap@5.3.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\">\n");
        }

        skeletonBuilder.append("  <link href=\"https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css\" rel=\"stylesheet\">\n");
        skeletonBuilder.append("  <!-- Fallback CDN -->\n");
        skeletonBuilder.append("  <link href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\" rel=\"stylesheet\">\n");

        skeletonBuilder.append("  <link href=\"https://cdn.jsdelivr.net/npm/animate.css@4.1.1/animate.min.css\" rel=\"stylesheet\">\n");
        skeletonBuilder.append("  <!-- Fallback CDN -->\n");
        skeletonBuilder.append("  <link href=\"https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css\" rel=\"stylesheet\">\n");

        skeletonBuilder.append("  <style>\n");

        // 添加CSS变量
        skeletonBuilder.append(pageStyle.generateCssVariables());

        // 添加基础样式
        skeletonBuilder.append("    body {\n");
        skeletonBuilder.append("      font-family: ").append(pageStyle.getFontFamily()).append(";\n");
        skeletonBuilder.append("      color: var(--text-color);\n");
        skeletonBuilder.append("      line-height: 1.6;\n");

        // 根据颜色方案设置背景
        if ("dark".equalsIgnoreCase(pageStyle.getColorScheme())) {
            skeletonBuilder.append("      background-color: var(--dark-bg);\n");
            skeletonBuilder.append("      color: #f8f9fa;\n");
        } else {
            skeletonBuilder.append("      background-color: var(--light-bg);\n");
        }

        skeletonBuilder.append("    }\n");

        // 添加组件通用样式
        skeletonBuilder.append("    .section-container {\n");
        skeletonBuilder.append("      margin-bottom: 2rem;\n");
        skeletonBuilder.append("    }\n");

        // 根据布局风格设置不同的卡片样式
        skeletonBuilder.append("    .card {\n");
        if ("minimal".equalsIgnoreCase(pageStyle.getLayoutStyle())) {
            skeletonBuilder.append("      border: none;\n");
            skeletonBuilder.append("      border-radius: 4px;\n");
            skeletonBuilder.append("      box-shadow: 0 1px 3px rgba(0,0,0,0.1);\n");
        } else if ("rich".equalsIgnoreCase(pageStyle.getLayoutStyle())) {
            skeletonBuilder.append("      border-radius: 12px;\n");
            skeletonBuilder.append("      overflow: hidden;\n");
            skeletonBuilder.append("      box-shadow: 0 8px 30px rgba(0,0,0,0.2);\n");
            skeletonBuilder.append("      transition: transform 0.4s ease, box-shadow 0.4s ease;\n");
        } else {
            // 默认clean风格
            skeletonBuilder.append("      border-radius: 8px;\n");
            skeletonBuilder.append("      overflow: hidden;\n");
            skeletonBuilder.append("      box-shadow: 0 4px 6px rgba(0,0,0,0.1);\n");
            skeletonBuilder.append("      transition: transform 0.3s ease, box-shadow 0.3s ease;\n");
        }
        skeletonBuilder.append("    }\n");

        skeletonBuilder.append("    .card:hover {\n");
        skeletonBuilder.append("      transform: translateY(-5px);\n");
        skeletonBuilder.append("      box-shadow: 0 10px 20px rgba(0,0,0,0.15);\n");
        skeletonBuilder.append("    }\n");

        // 按钮样式
        skeletonBuilder.append("    .btn-custom {\n");
        skeletonBuilder.append("      background-color: var(--primary-color);\n");
        skeletonBuilder.append("      border-color: var(--primary-color);\n");
        skeletonBuilder.append("      color: white;\n");
        skeletonBuilder.append("      border-radius: 4px;\n");
        skeletonBuilder.append("      padding: 8px 16px;\n");
        skeletonBuilder.append("      transition: all 0.3s ease;\n");
        skeletonBuilder.append("    }\n");
        skeletonBuilder.append("    .btn-custom:hover {\n");
        skeletonBuilder.append("      background-color: var(--secondary-color);\n");
        skeletonBuilder.append("      border-color: var(--secondary-color);\n");
        skeletonBuilder.append("      transform: translateY(-2px);\n");
        skeletonBuilder.append("    }\n");

        // 添加CSS占位符
        appendCssPlaceholders(skeletonBuilder, pageSections, 0);

        skeletonBuilder.append("  </style>\n");
        skeletonBuilder.append("</head>\n");

        // 根据颜色方案设置body类
        if ("dark".equalsIgnoreCase(pageStyle.getColorScheme())) {
            skeletonBuilder.append("<body class=\"bg-dark text-light\">\n");
        } else {
            skeletonBuilder.append("<body>\n");
        }

        // 添加HTML结构
        if (analysisContent != null && analysisContent.length() > 0) {
            // 如果有分析结果，使用分析结果作为HTML结构
            skeletonBuilder.append(analysisContent);
        } else {
            // 否则生成一个基本的结构
            skeletonBuilder.append("  <div class=\"container-fluid\">\n");
            skeletonBuilder.append("    <!-- 页面内容将在这里生成 -->\n");
            skeletonBuilder.append("  </div>\n");
        }

        // 添加必要的JavaScript库
        skeletonBuilder.append("\n  <!-- 必要的JavaScript库 -->\n");

        // 根据UI框架选择不同的JS库
        if ("bootstrap".equalsIgnoreCase(pageStyle.getUiFramework())) {
            skeletonBuilder.append("  <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/js/bootstrap.bundle.min.js\"></script>\n");
            skeletonBuilder.append("  <!-- Fallback CDN -->\n");
            skeletonBuilder.append("  <script src=\"https://unpkg.com/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js\"></script>\n");
        } else if ("material".equalsIgnoreCase(pageStyle.getUiFramework())) {
            skeletonBuilder.append("  <script src=\"https://cdn.jsdelivr.net/npm/@material/material-components-web@14.0.0/dist/material-components-web.min.js\"></script>\n");
            skeletonBuilder.append("  <!-- Fallback CDN -->\n");
            skeletonBuilder.append("  <script src=\"https://unpkg.com/@material/material-components-web@14.0.0/dist/material-components-web.min.js\"></script>\n");
        }

        skeletonBuilder.append("  <script src=\"https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js\"></script>\n");
        skeletonBuilder.append("  <!-- Fallback CDN -->\n");
        skeletonBuilder.append("  <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js\"></script>\n");

        // 添加JavaScript脚本区域
        skeletonBuilder.append("\n  <script>\n");
        skeletonBuilder.append("    // 页面加载完成后执行\n");
        skeletonBuilder.append("    document.addEventListener('DOMContentLoaded', function() {\n");
        skeletonBuilder.append("      console.log('页面已加载完成');\n");
        skeletonBuilder.append("      // 初始化代码将在这里添加\n");
        skeletonBuilder.append("    });\n");
        skeletonBuilder.append("  </script>\n");

        skeletonBuilder.append("</body>\n");
        skeletonBuilder.append("</html>");

        return skeletonBuilder.toString();
    }

    /**
     * 从需求中提取标题
     */
    private static String extractTitle(String requirements) {
        // 简单提取标题，默认为"生成页面"
        String title = "生成页面";

        // 尝试从需求中提取更具体的标题
        if (requirements.toLowerCase().contains("视频") || requirements.toLowerCase().contains("影片")) {
            title = "视频网站首页";
        } else if (requirements.toLowerCase().contains("电商") || requirements.toLowerCase().contains("购物")) {
            title = "电商网站首页";
        } else if (requirements.toLowerCase().contains("博客") || requirements.toLowerCase().contains("文章")) {
            title = "博客网站首页";
        } else if (requirements.toLowerCase().contains("新闻")) {
            title = "新闻网站首页";
        }

        return title;
    }

    /**
     * 添加CSS占位符
     */
    private static void appendCssPlaceholders(StringBuilder builder, List<PageSection> sections, int depth) {
        String indent = "    ".repeat(depth + 1);

        for (PageSection section : sections) {
            builder.append(indent).append("/*").append(section.getId()).append("*/\n");

            // 递归添加子部分的CSS占位符
            if (!section.getChildren().isEmpty()) {
                appendCssPlaceholders(builder, section.getChildren(), depth + 1);
            }
        }
    }

    /**
     * 将单个组件集成到骨架中
     *
     * @param sectionId 部分ID
     * @param componentContent 组件内容
     * @param skeletonCode 骨架代码
     * @return 更新后的骨架代码
     */
    public static String integrateComponentIntoSkeleton(String sectionId, String componentContent, StringBuilder skeletonCode) {
        logger.info("集成组件 {} 到骨架中，组件内容长度: {}", sectionId, componentContent.length());
        String skeleton = skeletonCode.toString();

        try {
            // 提取组件的各个部分
            String bodyContent = CodeGenerationUtil.extractComponentPart(componentContent, "body");
            String styleContent = CodeGenerationUtil.extractComponentPart(componentContent, "style");
            String scriptContent = CodeGenerationUtil.extractComponentPart(componentContent, "script");

            logger.debug("提取的组件部分 - body长度: {}, style长度: {}, script长度: {}",
                bodyContent.length(), styleContent.length(), scriptContent.length());

            // 1. 处理body部分 - 支持两种占位符格式
            boolean bodyInserted = false;

            // 格式1: <!-- SECTION: id --> 和 <!-- /SECTION: id -->
            String regexFormat1Start = "<!--\\s*SECTION:\\s*" + sectionId + "\\s*-->";
            String regexFormat1End = "<!--\\s*/SECTION:\\s*" + sectionId + "\\s*-->";

            Pattern startPattern1 = Pattern.compile(regexFormat1Start, Pattern.CASE_INSENSITIVE);
            Pattern endPattern1 = Pattern.compile(regexFormat1End, Pattern.CASE_INSENSITIVE);
            Matcher startMatcher1 = startPattern1.matcher(skeleton);
            Matcher endMatcher1 = endPattern1.matcher(skeleton);

            if (startMatcher1.find() && endMatcher1.find(startMatcher1.end())) {
                int startPos = startMatcher1.end();
                int endPos = endMatcher1.start();

                String before = skeleton.substring(0, startPos);
                String after = skeleton.substring(endPos);
                skeleton = before + "\n" + bodyContent + "\n" + after;
                bodyInserted = true;
                logger.debug("使用格式1成功插入组件 {} 的body内容", sectionId);
            }
            // 如果格式1未找到匹配，尝试直接在页面中查找合适位置插入
            else {
                // 查找任何可能包含该组件ID的注释
                Pattern anyMentionPattern = Pattern.compile("<!--.*?" + sectionId + ".*?-->", Pattern.CASE_INSENSITIVE);
                Matcher anyMentionMatcher = anyMentionPattern.matcher(skeleton);

                if (anyMentionMatcher.find()) {
                    // 在注释后插入组件
                    int insertPos = anyMentionMatcher.end();
                    String before = skeleton.substring(0, insertPos);
                    String after = skeleton.substring(insertPos);
                    skeleton = before + "\n" + bodyContent + "\n" + after;
                    bodyInserted = true;
                    logger.debug("在找到的注释后插入组件 {} 的body内容", sectionId);
                }
                // 如果仍然找不到，则在body标签内的适当位置插入
                else if (!bodyInserted) {
                    Pattern bodyTagPattern = Pattern.compile("<body[^>]*>", Pattern.CASE_INSENSITIVE);
                    Matcher bodyTagMatcher = bodyTagPattern.matcher(skeleton);

                    if (bodyTagMatcher.find()) {
                        int insertPos = bodyTagMatcher.end();
                        String before = skeleton.substring(0, insertPos);
                        String after = skeleton.substring(insertPos);

                        // 创建一个包装容器
                        String wrappedContent = "\n<!-- 自动插入的组件: " + sectionId + " -->\n" +
                                               "<div class=\"container my-4\">\n" +
                                               "  <div class=\"row\">\n" +
                                               "    <div class=\"col-12\">\n" +
                                               bodyContent + "\n" +
                                               "    </div>\n" +
                                               "  </div>\n" +
                                               "</div>\n";

                        skeleton = before + wrappedContent + after;
                        bodyInserted = true;
                        logger.debug("在body标签后插入组件 {} 的body内容", sectionId);
                    }
                }
            }

            if (!bodyInserted) {
                logger.warn("未能插入组件 {} 的body内容，找不到合适的插入点", sectionId);
            }

            // 2. 处理style部分
            if (styleContent != null && !styleContent.isEmpty()) {
                // 查找style标签
                Pattern styleTagPattern = Pattern.compile("</style>", Pattern.CASE_INSENSITIVE);
                Matcher styleTagMatcher = styleTagPattern.matcher(skeleton);

                if (styleTagMatcher.find()) {
                    // 在style标签关闭前插入样式
                    int insertPos = styleTagMatcher.start();
                    String before = skeleton.substring(0, insertPos);
                    String after = skeleton.substring(insertPos);

                    // 添加组件样式，并用注释标记
                    String wrappedStyle = "\n/* 组件样式: " + sectionId + " */\n" + styleContent + "\n\n";

                    skeleton = before + wrappedStyle + after;
                    logger.debug("成功插入组件 {} 的style内容", sectionId);
                } else {
                    logger.warn("未找到</style>标签，无法插入组件 {} 的样式", sectionId);
                }
            }

            // 3. 处理script部分
            if (scriptContent != null && !scriptContent.isEmpty()) {
                // 查找script标签内的DOMContentLoaded事件监听器
                Pattern domReadyPattern = Pattern.compile("document\\.addEventListener\\('DOMContentLoaded', function\\(\\)\\s*\\{", Pattern.CASE_INSENSITIVE);
                Matcher domReadyMatcher = domReadyPattern.matcher(skeleton);

                if (domReadyMatcher.find()) {
                    // 在事件监听器内部插入脚本
                    int insertPos = skeleton.indexOf("\n", domReadyMatcher.end());
                    if (insertPos == -1) insertPos = domReadyMatcher.end();

                    String before = skeleton.substring(0, insertPos);
                    String after = skeleton.substring(insertPos);

                    // 提取脚本中的初始化代码
                    String initCode = CodeGenerationUtil.extractInitCode(scriptContent);
                    String wrappedScript = "\n  // 组件初始化: " + sectionId + "\n  " +
                                          initCode.replace("\n", "\n  ") + "\n";

                    skeleton = before + wrappedScript + after;
                    logger.debug("在DOMContentLoaded事件中插入组件 {} 的初始化代码", sectionId);

                    // 提取函数定义并添加到脚本末尾
                    String functions = CodeGenerationUtil.extractFunctions(scriptContent);
                    if (!functions.isEmpty()) {
                        // 查找主script标签的结束位置
                        Pattern scriptEndPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE);
                        Matcher scriptEndMatcher = scriptEndPattern.matcher(skeleton);

                        if (scriptEndMatcher.find()) {
                            insertPos = scriptEndMatcher.start();
                            before = skeleton.substring(0, insertPos);
                            after = skeleton.substring(insertPos);

                            String wrappedFunctions = "\n// 组件函数: " + sectionId + "\n" +
                                                     functions + "\n\n";

                            skeleton = before + wrappedFunctions + after;
                            logger.debug("添加组件 {} 的函数定义", sectionId);
                        }
                    }
                } else {
                    // 如果找不到DOMContentLoaded事件，则在script标签结束前插入
                    Pattern scriptEndPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE);
                    Matcher scriptEndMatcher = scriptEndPattern.matcher(skeleton);

                    if (scriptEndMatcher.find()) {
                        int insertPos = scriptEndMatcher.start();
                        String before = skeleton.substring(0, insertPos);
                        String after = skeleton.substring(insertPos);

                        String wrappedScript = "\n// 组件脚本: " + sectionId + "\n" +
                                             scriptContent.trim() + "\n\n";

                        skeleton = before + wrappedScript + after;
                        logger.debug("在script标签结束前插入组件 {} 的完整脚本", sectionId);
                    } else {
                        logger.warn("未找到</script>标签，无法插入组件 {} 的脚本", sectionId);
                    }
                }
            }

            return skeleton;
        } catch (Exception e) {
            logger.error("集成组件 {} 时出错: {}", sectionId, e.getMessage(), e);
            return skeleton;
        }
    }
}
